package com.cwf.quality.common.strategy.filter;

import com.cwf.quality.common.enums.DataCheckFilterEnum;
import com.cwf.quality.model.dto.QualityResultInfo;
import com.cwf.quality.model.dto.datacheck.result.ValueRangeCheckResult;
import com.cwf.quality.model.dto.datacheck.rule.CheckRuleInfo;
import com.cwf.quality.model.dto.datacheck.rule.DataCheckRuleInfo;
import com.cwf.quality.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class ValueRangeCheckFilter implements IDataCheckFilter {

    /**
     * 校验超出取值范围
     *
     * @param dataCheckRuleInfo
     * @return
     */
    @Override
    public QualityResultInfo<List<ValueRangeCheckResult>> checkData(DataCheckRuleInfo dataCheckRuleInfo) {
        List<ValueRangeCheckResult> valueRangeCheckResultList = new ArrayList<>();

        List<CheckRuleInfo.ColumnRange> columnRangeList = dataCheckRuleInfo.getCheckRuleInfo().getColumnRangeList();
        SqlUtils sqlUtils = dataCheckRuleInfo.getSqlUtils();

        for (CheckRuleInfo.ColumnRange columnRange : columnRangeList) {
            Long min = columnRange.getMin();
            Long max = columnRange.getMax();
            String columnName = columnRange.getColumnName();
            String sql = DataCheckFilterEnum.VALUE_RANGE_CHECK.getSql()
                    .replace("{table}", dataCheckRuleInfo.getTableName())
                    .replace("{column}", columnName)
                    .replace("{min}", min.toString())
                    .replace("{max}", max.toString());

            List<Map<String, Object>> mapList = sqlUtils.query4List(sql, 1);
            Long count = (Long) mapList.get(0).get("over_range_count");
            valueRangeCheckResultList.add(ValueRangeCheckResult.builder().columnName(columnName).overRangeCount(count).build());
        }
        QualityResultInfo qualityResultInfo = QualityResultInfo.builder()
                .code(0)
                .msg("成功")
                .result(valueRangeCheckResultList)
                .build();
        return qualityResultInfo;
    }
}
